package com.yft.data.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yft.data.User;
import com.yft.data.service.BlackListService;
import com.yft.data.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private BlackListService blackListService;
	
	/**
	 * 添加黑名单
	 * @param userid
	 * @param phone
	 * @param corpid
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "getblcount", method = RequestMethod.GET)
	@ResponseBody
	public int getBlackListCount(
			@RequestParam(value = "userid", required = false) String userid,
			HttpServletRequest request,
			HttpSession session) {
		if(userid==null)
		{
			return blackListService.getBlackList().size();
		}else
		{
			return blackListService.getBlackList(userid).size();
		}
	}
	
	/**
	 * 添加黑名单
	 * @param userid
	 * @param phone
	 * @param corpid
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "addblacklist", method = RequestMethod.GET)
	@ResponseBody
	public String addBlackList(
			@RequestParam("userid") String userid,
			@RequestParam("phone") String phone,
			@RequestParam("corpid") Integer corpid, 
			HttpServletRequest request,
			HttpSession session) {
		if(blackListService.getBlackList().contains(phone)||blackListService.getBlackList(userid).contains(phone))
		{
			return "exist";
		}
		if (userService.find(corpid, userid)
				&& blackListService.isNotExpire(corpid, userid)) {
			blackListService.setBlock(phone, userid);
			return "success";
		}
		else
		{
			return "failed";
		}
	}

	/**
	 * @param userid
	 *            – 用户id
	 * @param corpid
	 *            – 商户id（亿房通为1）
	 * @param username
	 *            – 用户name
	 * @param cityid
	 *            – 用户所在城市id
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	@ResponseBody
	public String add(
			@RequestParam("userid") String userid,
			@RequestParam("username") String username,
			@RequestParam("corpid") Integer corpid,
			@RequestParam("cityid") Integer cityid,
			@RequestParam(value = "testdays", required = false) Integer testdays,
			HttpServletRequest request, HttpSession session) {
		if (testdays == null) {
			testdays = 30;
		} else if (testdays > 60) {
			testdays = 60;
		}
		try {
			username = new String(username.trim().getBytes("ISO-8859-1"),
					"utf-8");
		} catch (UnsupportedEncodingException e) {
			logger.debug("转码不成功", e);
		}
		// 如果已存在
		if (userService.find(corpid, userid)) {
			return "exist";
		}
		// 如果添加成功
		else if (userService.add(corpid, userid, username, cityid, testdays)) {
			return "success";
		} else {
			return "failed";
		}
	}

	/**
	 * @param userid
	 *            – 用户id
	 * @param corpid
	 *            – 商户id（亿房通为1）
	 * @param paynum
	 *            – 支付金额 float
	 * @param nextpaytime
	 *            – 有效期限（直到哪一天为止，含当天）格式：yyyyMMdd
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "pay", method = RequestMethod.GET)
	@ResponseBody
	public String pay(@RequestParam("userid") String userid,
			@RequestParam("corpid") Integer corpid,
			@RequestParam("paynum") Float paynum,
			@RequestParam("nextpaytime") String nextpaytime,
			HttpServletRequest request, HttpSession session) {

		if (userService.pay(corpid, userid, paynum, nextpaytime)) {
			return "success";
		} else {
			return "failed";
		}
	}

	// -------------------------------------------------//
	// 测试内容
	// -------------------------------------------------//
	/**
	 * 用户登录系统
	 * 
	 * @return
	 */
	@RequestMapping(value = "login")
	public ModelAndView login(HttpServletRequest request, HttpSession session) {

		User user = null;
		try {
			// TwiooID
			Integer twiooId = ServletRequestUtils.getIntParameter(request,
					"twiooId");
			// 群ID
			Integer groupId = ServletRequestUtils.getIntParameter(request,
					"groupId");
			session.setAttribute("user", user);
			session.setAttribute("twiooId", twiooId);
			session.setAttribute("groupId", groupId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("LoginController.login() execute error!!!");
		}
		return new ModelAndView("index");
	}

	/**
	 * 用户退出系统
	 * 
	 * @return
	 */
	@RequestMapping(value = "exit")
	public ModelAndView exit(HttpServletRequest request, HttpSession session) {

		session.removeAttribute("user");
		session.removeAttribute("twiooId");
		session.removeAttribute("groupId");
		return new ModelAndView("index");
	}

	/**
	 * 测试返回JSON数据
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "test")
	@ResponseBody
	public List<User> test(HttpSession session) {
		User user = new User();
		user.setName("刘亚非");
		user.setPass("123456");
		List<User> list = new ArrayList<User>();
		list.add(user);
		User user2 = new User();
		user2.setName("test");
		user2.setPass("123");
		list.add(user2);
		return list;
	}
}